package com.jimmyhsu.ecnudaowei.coursetable.bulletin;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jimmyhsu.ecnudaowei.MyApplication;
import com.jimmyhsu.ecnudaowei.R;
import com.jimmyhsu.ecnudaowei.common.Config;
import com.jimmyhsu.ecnudaowei.common.activities.BigPhotoActivity;
import com.jimmyhsu.ecnudaowei.login.LoginActivity;
import com.jimmyhsu.ecnudaowei.secondhand.SecondHandDetailActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public class BulletinDetailActivity extends AppCompatActivity {

    private static final String EXTRA_TITLE = "extra_title";
    private static final String EXTRA_CONTENT = "extra_content";
    private static final String EXTRA_AUTHOR = "extra_author";
    private static final String EXTRA_RELEASE_TIME = "extra_release_time";
    private static final String EXTRA_IMG_URL = "extra_img_url";
    private static final String EXTRA_COURSE_ID = "extra_course_id";
    private static final String EXTRA_BID = "extra_bid";

    @BindView(R.id.id_abd_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_abd_title)
    TextView titleView;
    @BindView(R.id.id_abd_content)
    TextView contentView;
    @BindView(R.id.id_abd_author)
    TextView authorView;
    @BindView(R.id.id_abd_release_time)
    TextView releaseTimeView;
    @BindView(R.id.id_abd_modify)
    TextView modifyView;
    @BindView(R.id.id_abd_img)
    ImageView imageView;

    private MyApplication mApp;

    private boolean isAuthor = false;
    private String mCourseId;
    private int mBId;
    private String mTitle;
    private String mContent;
    private String mImageUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bulletin_detail);
        ButterKnife.bind(this);
        mApp = MyApplication.getInstance(this);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("");
        initDatas();
    }

    private void initDatas() {
        Intent data = getIntent();
        if (data != null) {
            titleView.setText(mTitle = data.getStringExtra(EXTRA_TITLE));
            contentView.setText(mContent = data.getStringExtra(EXTRA_CONTENT));
            authorView.setText(data.getStringExtra(EXTRA_AUTHOR));
            String dateStr = data.getStringExtra(EXTRA_RELEASE_TIME);
            mCourseId = data.getStringExtra(EXTRA_COURSE_ID);
            mBId = data.getIntExtra(EXTRA_BID, -1);
            dateStr = dateStr.replaceFirst("-", "年");
            dateStr = dateStr.replaceFirst("-", "月");
            dateStr = dateStr.replaceFirst(" ", "日 ");
            dateStr = dateStr.substring(0, dateStr.length() - 3);
            releaseTimeView.setText(dateStr);
            mImageUrl = data.getStringExtra(EXTRA_IMG_URL);
            if (mImageUrl.length() > 0) {
                imageView.setVisibility(View.VISIBLE);
                Glide.with(this).load(Config.SERVER_URL + mImageUrl)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .skipMemoryCache(true)
                        .centerCrop().into(imageView);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ActivityOptionsCompat options =
                                ActivityOptionsCompat.makeScaleUpAnimation(imageView,
                                        (int)imageView.getWidth()/2, (int)imageView.getHeight()/2,
                                        0, 0);//拉伸开始的区域大小，这里用（0，0）表示从无到全屏
                        BigPhotoActivity.startActivity(BulletinDetailActivity.this, Config.SERVER_URL + mImageUrl, options.toBundle());
                    }
                });
            }
            if (data.getStringExtra(EXTRA_AUTHOR).equals(mApp.getRealName())) {
                isAuthor = true;
                modifyView.setVisibility(View.VISIBLE);
                invalidateOptionsMenu();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isAuthor) {
            MenuItem item = menu.add(0, 0, 0, "删除");
            item.setIcon(R.drawable.ic_delete_white_36dp);
            item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        } else if (item.getItemId() == 0) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(Config.SERVER_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .build();
            ModifyBulletinService service = retrofit.create(ModifyBulletinService.class);
            Call<String> call = service.deleteBulletin(mApp.getName(),
                    mApp.getPassword(),
                    mCourseId,
                    String.valueOf(mBId));
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if (response.code() == 200) {
                        Log.e("haha", "body: " + response.body());
                        if ("success".equals(response.body())) {
                            Toast.makeText(BulletinDetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(BulletinDetailActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    Toast.makeText(BulletinDetailActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            });
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.id_abd_modify)
    void modifyBulletin() {
        AddBulletinActivity.startActivity(this, mCourseId, mBId, mTitle, mContent, mImageUrl);
    }

    public static void startActivity(Context context, String courseId,
                                     int bId, String title, String content,
                                     String author, String releaseTime, String imgUrl) {
        Intent intent = new Intent(context, BulletinDetailActivity.class);
        intent.putExtra(EXTRA_TITLE, title)
                .putExtra(EXTRA_CONTENT, content)
                .putExtra(EXTRA_AUTHOR, author)
                .putExtra(EXTRA_RELEASE_TIME, releaseTime)
                .putExtra(EXTRA_IMG_URL, imgUrl)
                .putExtra(EXTRA_COURSE_ID, courseId)
                .putExtra(EXTRA_BID, bId);
        context.startActivity(intent);

    }

    interface ModifyBulletinService {
        @FormUrlEncoded
        @POST("phpprojects/course/deleteBulletin.php")
        Call<String> deleteBulletin(@Field("username") String username,
                                    @Field("password") String password,
                                    @Field("course_id") String courseId,
                                    @Field("b_id") String bId);
    }
}
